﻿

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetCore.Ado;
using NetCore.WF.BLL.Domain;
using NetCore.WF.Model;
namespace NetCore.WF.BLL
{
    public partial class FlowService : SerivceBase, IFlowService
    {
        public const string Flow_Identity_Num = "0012";

        public string RootPath {
            get {
                return ApplicationEnvironments.BaseDirectory + ApplicationEnvironments.Site.ConfigFile.configPath+ "flow/";
            }
        }
        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<FlowEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(FlowEntity.__IsDeleted, false);
            return this.Query<FlowEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public FlowEntity GetById(object id)
        {
            return this.GetById<FlowEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(FlowEntity entity, ref string strError)
        {
            if (Exist(entity.FlowName, entity.FlowId))
            {
                strError = entity.FlowName + "已存在，请不要重复输入";
                return false;
            }
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            keyValuePairs.Add("FlowType",entity.FlowTypeId);
             entity.FlowId = new NetCore.BLL.SerialRuleService().CreateSerialNo(Flow_Identity_Num, keyValuePairs, ref strError);// 主键生成值
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<FlowEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid grid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(grid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                FlowEntity._PrimaryKeyName ,
                                FlowEntity.__FlowName
                           }, grid.keyWord)
                           );
            }
           
            return this.Query<FlowEntity>(grid, criter);

        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 验证是否存在的方法
        /// <param name="name">需要验证的值</param>
        /// <param name="key">主键</param>
        /// </summary>
        public bool Exist(string name, string key)
        {
            key = (string.IsNullOrWhiteSpace(key)) ? "" : key;

            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter =
                Expression.And(criter, Expression.And(Expression.Eq(FlowEntity.__FlowName, name),
                Expression.Not(Expression.Eq(FlowEntity._PrimaryKeyName, key)))
                );
            var result = this.Query<FlowEntity>(criter).FirstOrDefault();
            return result != null;
        }
        /// <summary>
        /// 获取结构树列表
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public List<FlowTypeEntity> GetTree(string parentid,int isType)
        {
            if (!string.IsNullOrWhiteSpace(parentid)&& parentid.Equals("#"))
            {
                return new List<FlowTypeEntity>() {
                    new FlowTypeEntity{
                         FlowTypeId="0",
                         parent="#",
                          FlowTypeName="工作流",
                          IsType=0,
                          icon="fa fa-tree"
                          ,children=true
                    }
                };
            }
           var tService = new FlowTypeService();
           var lstChildren=  tService.GetChildren(parentid);
            if (lstChildren != null && lstChildren.Count > 0)
            {
                lstChildren.ForEach(x =>
                {
                    x.IsType = 1;
                    x.parent = (string.IsNullOrWhiteSpace(x.ParentId) ? "0" : x.ParentId);
                    x.icon = "fa fa-gear";
                    x.children = true;

                });
            }
            else {
                lstChildren = new List<FlowTypeEntity>();
            }
            if (isType<2&&!string.IsNullOrWhiteSpace(parentid) && !parentid.Equals("0"))
            {
                ICriterion criter = Expression.And(Expression.Eq(FlowEntity.__FlowTypeId, parentid), Expression.Eq("IsDeleted", false));
                var lstFlow = this.Query<FlowEntity>(criter);
                if (lstFlow == null)
                {
                    lstFlow = new List<FlowEntity>();
                }
                var lstFlowTemp = this.GetTempAllFlow();
                if (lstFlowTemp != null)
                {
                    foreach (var temp in lstFlowTemp)
                    {
    
                       int index = lstFlow.FindIndex(x => x.FlowId == temp.Flow.FlowId);
                        if (index>=0)
                        {
                            lstFlow[index] = temp.Flow;
                        }
                        else
                        {
                            lstFlow.Add(temp.Flow);
                        }
                    }
                }
                if (lstFlow != null)
                {
                    
                    List<FlowTypeEntity> flowTypes = (from x in lstFlow
                                                      where x.FlowTypeId==parentid 
                        select new FlowTypeEntity
                        {
                            FlowTypeId = x.FlowId,
                            OrderNum = x.OrderNum,
                            IsType = 2,
                            FlowTypeName = x.FlowName,
                            parent = parentid,
                            children = true,
                            IsCheckOut=x.IsCheckOut,
                            IsEdited =x.IsCheckOut&& x.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId),
                            icon = (x.IsCheckOut ) ? (x.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId)? "fa fa-user": "fa fa-lock") : "fa fa-check"

                }).ToList();
                    lstChildren = lstChildren.Union(flowTypes).ToList();
                }
            }
           else  if (isType == 2)
            {
              var  criter = Expression.And(Expression.Eq(FlowVersionEntity.__FlowId, parentid), Expression.Eq("IsDeleted", false));
                var lstFlowVersion = this.Query<FlowVersionEntity>(criter);
                if (lstFlowVersion != null)
                {
                    List<FlowTypeEntity> flowTypes =
                        (from x in lstFlowVersion
                         select new FlowTypeEntity
                         {
                             FlowTypeId = x.FlowVersionId,
                             OrderNum = x.Version,
                             IsType = 3,
                             FlowTypeName = "V_"+ x.Version.ToString(),
                             icon = "fa fa-leaf",
                             parent = x.FlowId,
                             children = false,
                             IsCheckOut=false,
                             IsEdited=false
                         }).ToList();
                    lstChildren = lstChildren.Union(flowTypes).ToList();
                }
            }
            return lstChildren;
        }

        /// <summary>
        /// 获取流程图
        /// </summary>
        /// <param name="flowid"></param>
        /// <param name="isType"></param>
        /// <param name="version"></param>
        /// <returns></returns>
       public FlowEntity GetFlowDesigner(string flowid,  int version) {
            if (version<=0)
            {
                
            }
            return this.GetById(flowid);
        }

        /// <summary>
        /// 获取流程版本
        /// </summary>
        /// <param name="flowid"></param>
        /// <returns></returns>
        public List<FlowVersionEntity> GetFlowVersions(string flowid)
        {
            if (string.IsNullOrWhiteSpace(flowid))
            {
                return null;
            }
            var criter = Expression.And(Expression.Eq(FlowVersionEntity.__FlowId, flowid), Expression.Eq("IsDeleted", false));
            return this.Query<FlowVersionEntity>(criter);
        }
       
        #endregion
   


    }
}